package com.Jano.filter;/**
 * @ClassName : JwtAuthenticationTokenFilter
 * @Description :
 * @Author : Jano
 * @Date: 2022-07-24 22:13
 */

import com.Jano.dto.LoginUser;
import com.Jano.exception.BusinessException;
import com.Jano.util.JwtTokenUtil;
import com.Jano.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 保证请求只经过一次过滤器
 * @author zoumaoji
 * @date 2022/07/24 22:13
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isBlank(token)){
            //放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            //防止回来访问这个过滤器的时候会执行下面的方法
            return;
        }
        //解析token
        Claims claimsFromToken = JwtTokenUtil.getClaimsFromToken(token);
        String userId = claimsFromToken.getSubject();

        //从redis中获取用户信息
        String redisKey ="login:"+userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            throw new BusinessException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息 封装到AuthenticationToken
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser,
                null,
                loginUser.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
